<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Db;

/**
 * 公告管理
 * Class Slide
 * @package app\admin\controller
 */
class Notice extends AdminBase
{

    protected function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 公告管理
     * @return mixed
     */
    public function index()
    {
        $notice_list  = Db::name('notice')->where('del_time',null)->select();
        foreach ($notice_list as $k=>$v){
            $notice_list[$k]['add_time'] = date('Y-m-d H:i',$v['add_time']);
        }
        return $this->fetch('index', ['notice_list' => $notice_list]);
    }

    /**
     * 添加公告
     * @return mixed
     */
    public function add()
    {
        return $this->fetch('add');
    }

    /**
     * 保存公告
     */
    public function save()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            if(!isset($data['content'])||empty($data['content'])){
                $this->error('请填写公告内容');
            }
            if(!isset($data['title'])||empty($data['title'])){
                $this->error('请填写公告标题');
            }
            $save = [
                'content' => $data['content'],
                'title' => $data['title'],
                'add_time' => time(),
            ];
            $r = Db::name('notice')->insertGetId($save);
            if ($r) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }

        }
    }

    /**
     * 编辑公告
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {
        $notice = Db::name('notice')->where('del_time',null)->where('id',$id)->find();

        return $this->fetch('edit', ['notice' => $notice]);
    }

    /**
     * 更新公告
     * @param $id
     */
    public function update($id)
    {
        if ($this->request->isPost()) {
            $data            = $this->request->param();
            if(!isset($data['content'])||empty($data['content'])){
                $this->error('请填写公告内容');
            }
            if(!isset($data['title'])||empty($data['title'])){
                $this->error('请填写公告标题');
            }
            $save = [
                'id' => $data['id'],
                'content' => $data['content'],
                'title' => $data['title'],
            ];
            $r = Db::name('notice')->update($save);
            if ($r) {
                $this->success('更新成功');
            } else {
                $this->error('更新失败');
            }
        }
    }

    /**
     * 删除公告
     * @param $id
     */
    public function delete($id)
    {
        if (Db::name('notice')->update(['id'=>$id,'del_time'=>time()])) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}